package com.huahai.controller;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.huahai.annotation.AuthCheck;
import com.huahai.api.ImageSearchApiFacade;
import com.huahai.api.aliyunai.model.CreateOutPaintingTaskResponse;
import com.huahai.api.aliyunai.model.GetOutPaintingTaskResponse;
import com.huahai.api.aliyunai.sub.ALiYunAIApi;
import com.huahai.api.imagesearch.model.ImageSearchResult;
import com.huahai.common.BaseResponse;
import com.huahai.common.DeleteRequest;
import com.huahai.constant.PictureReviewStatusConstant;
import com.huahai.constant.RedisConstant;
import com.huahai.constant.UserConstant;
import com.huahai.exception.BusinessException;
import com.huahai.exception.ErrorCode;
import com.huahai.manager.auth.SpaceUserAuthManager;
import com.huahai.manager.auth.StpKit;
import com.huahai.manager.auth.annotation.SaSpaceCheckPermission;
import com.huahai.manager.auth.constants.SpaceUserPermissionConstant;
import com.huahai.pojo.dto.picture.*;
import com.huahai.pojo.entity.Picture;
import com.huahai.pojo.entity.Space;
import com.huahai.pojo.entity.User;
import com.huahai.pojo.enums.PictureReviewStatusEnums;
import com.huahai.pojo.vo.picture.PictureTagCategoryVO;
import com.huahai.pojo.vo.picture.PictureVO;
import com.huahai.service.PictureService;
import com.huahai.service.SpaceService;
import com.huahai.service.UserService;
import com.huahai.util.ResultUtils;
import com.huahai.util.ThrowUtils;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.List;

/**
 * 图片相关接口
 *
 * @author huahai
 */
@RestController
@RequestMapping("/picture")
@Slf4j
public class PictureController {

    @Resource
    private PictureService pictureService;

    @Resource
    private UserService userService;

    @Resource
    private SpaceService spaceService;

    @Resource
    SpaceUserAuthManager spaceUserAuthManager;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private ALiYunAIApi aLiYunAiApi;

    // 图片浏览次数缓存 key
    private final String PICTURE_VIEW_COUNT_KEY = RedisConstant.PROJECT_NAME + RedisConstant.VIEW_COUNT;

    // 图片点赞数缓存 key
    private final String PICTURE_LIKE_COUNT_KEY = RedisConstant.PROJECT_NAME + RedisConstant.LIKE_COUNT;

    // 图片点赞列表缓存 key
    private final String PICTURE_LIKE_LIST_KEY = RedisConstant.PROJECT_NAME + RedisConstant.LIKED_USER_LIST;

    /**
     * 图片上传 (管理员) - 本地上传
     *
     * @param multipartFile    图片信息
     * @param pictureUploadDTO 图片上传信息（id）
     * @param request          请求
     * @return 封装后的图片信息
     */
    @ApiOperation(value = "图片上传(本地上传)")
    @PostMapping("/upload")
    @SaSpaceCheckPermission(value = SpaceUserPermissionConstant.PICTURE_UPLOAD)
//    图片上传功能开放给所有用户，添加审核功能进行限制
//    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<PictureVO> uploadPicture(@RequestPart("file") MultipartFile multipartFile,
                                                 PictureUploadDTO pictureUploadDTO,
                                                 HttpServletRequest request) {
        // 获取当前登录用户
        User loginUser = userService.getLoginUser(request);
        PictureVO pictureVO = pictureService.uploadPicture(multipartFile, pictureUploadDTO, loginUser);
        return ResultUtils.success(pictureVO);
    }

    /**
     * 图片上传 - url上传图片
     *
     * @param pictureUploadDTO 图片上传信息（id）
     * @param request          请求
     * @return 封装后的图片信息
     */
    @ApiOperation(value = "图片上传(url 上传)")
    @PostMapping("/upload/url")
    @SaSpaceCheckPermission(value = SpaceUserPermissionConstant.PICTURE_UPLOAD)
//    图片上传功能开放给所有用户，添加审核功能进行限制
//    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<PictureVO> uploadPictureByUrl(@RequestBody PictureUploadDTO pictureUploadDTO,
                                                      HttpServletRequest request) {
        // 获取当前登录用户
        User loginUser = userService.getLoginUser(request);
        String fileUrl = pictureUploadDTO.getFileUrl();
        if (StrUtil.isBlank(fileUrl)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        PictureVO pictureVO = pictureService.uploadPicture(fileUrl, pictureUploadDTO, loginUser);
        return ResultUtils.success(pictureVO);
    }

    /**
     * 删除图片
     *
     * @param deleteRequest 删除参数
     * @param request       请求
     * @return 删除结果
     */
    @ApiOperation(value = "根据id删除单张图片")
    @Transactional(rollbackFor = Exception.class)
    @PostMapping("/delete")
    @SaSpaceCheckPermission(value = SpaceUserPermissionConstant.PICTURE_DELETE)
    public BaseResponse<Boolean> deletePicture(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        // 参数校验
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 获取当前登录用户
        User loginUser = userService.getLoginUser(request);
        Boolean deleteResult = pictureService.deletePicture(deleteRequest, loginUser);
        return ResultUtils.success(deleteResult);
    }

    /**
     * 更新图片（仅管理员可用）
     *
     * @param pictureUpdateDTO 图片更新信息
     * @return 更新结果
     */
    @ApiOperation(value = "更新图片")
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updatePicture(@RequestBody PictureUpdateDTO pictureUpdateDTO, HttpServletRequest request) {
        // 1. 校验参数
        if (pictureUpdateDTO == null || pictureUpdateDTO.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 2. 将实体类和 DTO 进行转换
        Picture picture = new Picture();
        BeanUtils.copyProperties(pictureUpdateDTO, picture);
        // 注意将 list 转为 string
        picture.setTags(JSONUtil.toJsonStr(pictureUpdateDTO.getTags()));
        // 5.2 填补审核参数
        User loginUser = userService.getLoginUser(request);
        pictureService.fillReviewParams(picture, loginUser);
        // 3. 图片数据校验
        pictureService.validPicture(picture);
        // 4. 判断图片是否存在
        long id = pictureUpdateDTO.getId();
        Picture oldPicture = pictureService.getById(id);
        ThrowUtils.throwIf(oldPicture == null, ErrorCode.NOT_FOUND_ERROR);
//        // 指定 spaceId, 防止分库分表导致找不到图片对应空间
//        // 构造 UpdateWrapper
//        UpdateWrapper<Picture> updateWrapper = new UpdateWrapper<>();
//        updateWrapper.eq("id", picture.getId()) // 指定主键条件，批量更新则使用 in 传递多条
//                .eq("spaceId", oldPicture.getSpaceId());      // 补充条件 spaceId=xxx
//
//        // 执行更新
//        boolean result = pictureService.update(picture, updateWrapper);

        // 5. 操作数据库，执行修改操作
        boolean result = pictureService.updateById(picture);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        // 6. 修改成功，清理缓存
        pictureService.cleanCaffeineAndRedisCache();
        return ResultUtils.success(true);
    }

    /**
     * 根据 id 获取图片（仅管理员可用）
     *
     * @param id      图片 id
     * @param request 请求
     * @return 图片信息
     */
    @ApiOperation(value = "根据 id 获取完整图片信息(管理员)")
    @GetMapping("/get")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Picture> getPictureById(long id, HttpServletRequest request) {
        // 1. 校验参数
        ThrowUtils.throwIf(id <= 0, ErrorCode.PARAMS_ERROR);
        // 2. 查询数据库
        Picture picture = pictureService.getById(id);
        ThrowUtils.throwIf(picture == null, ErrorCode.NOT_FOUND_ERROR);
        // 指定 spaceId, 防止分库分表导致找不到图片对应空间
//        // 构造 QueryWrapper
//        QueryWrapper<Picture> queryWrapper = new QueryWrapper<>();
//        queryWrapper.eq("id", id)         // 根据主键 id 查询
//                .eq("spaceId", spaceId); // 附加 spaceId 条件
//
//        // 执行查询
//        Picture picture = pictureService.getOne(queryWrapper);
        // 3. 获取封装类,不脱敏的图片信息
        // 获取当前登录用户
        User loginUser = userService.getLoginUser(request);
        // 优先从 redis 缓存中获取图片的浏览量点赞数和点赞用户列表（数据库里不一定更新了浏览量点赞数和点赞用户列表）
        String viewCountStr = stringRedisTemplate.opsForValue().get(PICTURE_VIEW_COUNT_KEY + id);
        if (StrUtil.isNotBlank(viewCountStr)) {
            picture.setViewCount(Long.valueOf(viewCountStr));
        }
        String likeCountStr = stringRedisTemplate.opsForValue().get(PICTURE_LIKE_COUNT_KEY + id);
        if(StrUtil.isNotBlank(likeCountStr)){
            picture.setLikeCount(Long.valueOf(likeCountStr));
        }
        Boolean isLike = pictureService.checkPictureLiked(PictureVO.objToVo( picture), loginUser);
        picture.setIsLike(isLike);
        return ResultUtils.success(picture);
    }

    /**
     * 根据 id 获取图片（封装类 普通用户使用）
     *
     * @param id      图片 id
     * @param request 请求
     * @return 脱敏的图片信息
     */
    @ApiOperation(value = "根据 id 获取脱敏后的图片(普通用户)")
    @GetMapping("/get/vo")
    public BaseResponse<PictureVO> getPictureVOById(long id, HttpServletRequest request) {
        // 1. 校验参数
        ThrowUtils.throwIf(id <= 0, ErrorCode.PARAMS_ERROR);
        // 2. 查询数据库
        Picture picture = pictureService.getById(id);
        // 3. 校验空间权限
        Long spaceId = picture.getSpaceId();
        Space space = null;
        if (spaceId != null) {
            // 改为 Sa-Token 编程式鉴权
            boolean hasPermission = StpKit.SPACE.hasPermission(SpaceUserPermissionConstant.PICTURE_VIEW);
            ThrowUtils.throwIf(!hasPermission, ErrorCode.NO_AUTH_ERROR);
            space = spaceService.getById(spaceId);
            ThrowUtils.throwIf(space == null, ErrorCode.NOT_FOUND_ERROR, "空间不存在");
            // 私有图库，获取当前登录用户
//            User loginUser = userService.getLoginUser(request);
//            pictureService.checkPictureAuth(picture, loginUser);
        }
        // 表示公共图库
        if (spaceId == null) {
            // 4. 不允许查看审核未通过的图片
            if (!picture.getReviewStatus().equals(PictureReviewStatusConstant.PASS)) {
                throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
            }
        }
        ThrowUtils.throwIf(picture == null, ErrorCode.NOT_FOUND_ERROR);
        // 获取当前登录用户
        User loginUser = userService.getLoginUser(request);
        // 定义返回给前端的权限列表
        List<String> permissionList = spaceUserAuthManager.getPermissionList(space, loginUser);
        PictureVO pictureVO = pictureService.getPictureVO(picture, request);
        pictureVO.setPermissionList(permissionList);
        // 优先从 redis 缓存中获取图片的浏览量点赞数和点赞用户列表（数据库里不一定更新了浏览量点赞数和点赞用户列表）
        String viewCountStr = stringRedisTemplate.opsForValue().get(PICTURE_VIEW_COUNT_KEY + id);
        if (StrUtil.isNotBlank(viewCountStr)) {
            pictureVO.setViewCount(Long.valueOf(viewCountStr));
        }
        String likeCountStr = stringRedisTemplate.opsForValue().get(PICTURE_LIKE_COUNT_KEY + id);
        if(StrUtil.isNotBlank(likeCountStr)){
            pictureVO.setLikeCount(Long.valueOf(likeCountStr));
        }
        Boolean isLike = pictureService.checkPictureLiked(pictureVO, loginUser);
        pictureVO.setIsLike(isLike);
        // 5. 获取封装类
        return ResultUtils.success(pictureVO);
    }

    /**
     * 分页获取未脱敏图片列表（仅管理员可用）
     *
     * @param pictureQueryDTO 图片查询参数
     * @return 图片列表
     */
    @ApiOperation(value = "分页获取未脱敏图片列表(管理员)")
    @PostMapping("/list/page")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<Picture>> listPictureByPage(@RequestBody PictureQueryDTO pictureQueryDTO, HttpServletRequest request) {
        // 1. 获取分页参数
        long current = pictureQueryDTO.getCurrent();
        long size = pictureQueryDTO.getPageSize();
        // 2. 查询数据库
        Page<Picture> picturePage = pictureService.page(new Page<>(current, size),
                pictureService.getQueryWrapper(pictureQueryDTO));
        // 2.1 获取图片的浏览量
        // 获取当前登录用户
        User loginUser = userService.getLoginUser(request);
        // 优先从 redis 缓存中获取图片的浏览量（数据库里不一定更新了浏览量）
        // 优先从 redis 缓存中获取图片的点赞数和点赞列表 redis 缓存里不一定更新了点赞数和点赞列表）
        pictureService.fillPictureInfoFromRedis(picturePage, loginUser);
        // 3. 返回不脱敏的图片信息列表
        return ResultUtils.success(picturePage);
    }

    /**
     * 分页获取图片列表（封装类）
     *
     * @param pictureQueryDTO 图片查询参数
     * @param request         请求
     * @return 分页后的脱敏图片列表
     */
    @ApiOperation(value = "分页获取脱敏后的图片列表")
    @PostMapping("/list/page/vo")
    public BaseResponse<Page<PictureVO>> listPictureVOByPage(@RequestBody PictureQueryDTO pictureQueryDTO, HttpServletRequest request) {
        // 1. 获取分页参数
        long current = pictureQueryDTO.getCurrent();
        long size = pictureQueryDTO.getPageSize();
        // 2. 定义一次性最大获取图片数量，限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR, "获取图片数量超过限制！");
        // 3. 判断空间权限校验
        Long spaceId = pictureQueryDTO.getSpaceId();
        if (spaceId == null) {
            // 表示公共图库
            // 3.1 过滤未审核通过的图片
            pictureQueryDTO.setReviewStatus(PictureReviewStatusEnums.PASS.getValue());
            // 只查询spaceId为空的图片
            pictureQueryDTO.setNullSpaceId(true);
        } else {
            // 表示私有图库
            // 改为 Sa-Token 编程式鉴权
            boolean hasPermission = StpKit.SPACE.hasPermission(SpaceUserPermissionConstant.PICTURE_VIEW);
            ThrowUtils.throwIf(!hasPermission, ErrorCode.NO_AUTH_ERROR);
//            // 3.2 校验当前登录用户权限
//            User loginUser = userService.getLoginUser(request);
//            Space space = spaceService.getById(spaceId);
//            ThrowUtils.throwIf(space == null, ErrorCode.NOT_FOUND_ERROR, "空间不存在");
//            if (!loginUser.getId().equals(space.getUserId())) {
//                throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "您无权限操作此空间");
//            }
        }
        // 4. 查询数据库
        Page<Picture> picturePage = pictureService.page(new Page<>(current, size),
                pictureService.getQueryWrapper(pictureQueryDTO));
        // 5. 获取封装类并返回
        Page<PictureVO> pictureVoPage = pictureService.getPictureVoPage(picturePage);
        // 获取当前登录用户
        User loginUser = userService.getLoginUser(request);
        // 优先从 redis 缓存中获取图片的浏览量（数据库里不一定更新了浏览量）
        // 优先从 redis 缓存中获取图片的点赞数和点赞列表 redis 缓存里不一定更新了点赞数和点赞列表）
        pictureService.fillPictureInfoFromRedis(pictureVoPage, loginUser);
        return ResultUtils.success(pictureVoPage);
    }

    /**
     * 分页获取图片列表（封装类）利用多级缓存提升性能 (当前使用，对于私人空间可能没用必要使用)
     *
     * @param pictureQueryDTO 图片查询参数
     * @param request         请求
     * @return 分页后的脱敏图片列表
     */
    @ApiOperation(value = "分页获取脱敏后的图片列表（多级缓存封装）")
    @PostMapping("/list/page/vo/cache")
    public BaseResponse<Page<PictureVO>> listPictureVOByPageByCache(@RequestBody PictureQueryDTO pictureQueryDTO, HttpServletRequest request) {
        // 校验参数
        ThrowUtils.throwIf(pictureQueryDTO == null, ErrorCode.PARAMS_ERROR);
        Page<PictureVO> pictureVOPage = pictureService.listPictureVOByPageByCache(pictureQueryDTO, request);
        // 获取封装类并返回
        return ResultUtils.success(pictureVOPage);
    }

    /**
     * 编辑图片（给用户使用）
     *
     * @param pictureEditDTO 图片编辑信息
     * @param request        请求
     * @return 编辑结果
     */
    @ApiOperation(value = "编辑图片（用户使用）")
    @PostMapping("/edit")
    @SaSpaceCheckPermission(value = SpaceUserPermissionConstant.PICTURE_EDIT)
    public BaseResponse<Boolean> editPicture(@RequestBody PictureEditDTO pictureEditDTO, HttpServletRequest request) {
        // 校验参数
        if (pictureEditDTO == null || pictureEditDTO.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 获取当前登录用户
        User loginUser = userService.getLoginUser(request);
        Boolean editResult = pictureService.editPicture(pictureEditDTO, loginUser);
        return ResultUtils.success(editResult);
    }

    /**
     * 图片审核 (管理员)
     *
     * @param pictureReviewDTO 图片审核信息
     * @param request          请求
     * @return 修改结果
     */
    @ApiOperation(value = "图片状态审核")
    @PostMapping("/review")
    public BaseResponse<Boolean> doReviewPicture(@RequestBody PictureReviewDTO pictureReviewDTO, HttpServletRequest request) {
        ThrowUtils.throwIf(pictureReviewDTO == null, ErrorCode.PARAMS_ERROR);
        // 获取当前登录用户
        User loginUser = userService.getLoginUser(request);
        pictureService.doReviewPicture(pictureReviewDTO, loginUser);
        return ResultUtils.success(true);
    }


    /**
     * 预定分类的标签和图片类型的标签
     *
     * @return 分类标签和图片标签
     */
    @ApiOperation(value = "获取预定分类的标签和图片类型的标签")
    @GetMapping("/tag_category")
    public BaseResponse<PictureTagCategoryVO> listPictureTagCategory() {
        PictureTagCategoryVO pictureTagCategory = new PictureTagCategoryVO();
        List<String> tagList = Arrays.asList("热门", "搞笑", "生活", "高清", "艺术", "校园", "背景", "动漫", "创意");
        List<String> categoryList = Arrays.asList("模板", "电商", "表情包", "素材", "海报", "生活", "动漫");
        pictureTagCategory.setTagList(tagList);
        pictureTagCategory.setCategoryList(categoryList);
        return ResultUtils.success(pictureTagCategory);
    }

    /**
     * 批量抓取网络图片接口 （仅管理员可用）
     *
     * @param pictureUploadByBatchDTO 图片上传参数
     * @param request                 请求
     * @return 抓取数量
     */
    @ApiOperation(value = "批量抓取网络图片")
    @PostMapping("/upload/batch")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Integer> uploadPictureByBatch(
            @RequestBody PictureUploadByBatchDTO pictureUploadByBatchDTO,
            HttpServletRequest request
    ) {
        ThrowUtils.throwIf(pictureUploadByBatchDTO == null, ErrorCode.PARAMS_ERROR);
        User loginUser = userService.getLoginUser(request);
        int uploadCount = pictureService.uploadPictureByBatch(pictureUploadByBatchDTO, loginUser);
        return ResultUtils.success(uploadCount);
    }


    /**
     * 以图搜图功能接口
     *
     * @param searchPictureByPictureDTO 以图搜图请求参数
     * @return 相似图片的搜索结果
     */
    @ApiOperation(value = "以图搜图功能接口")
    @PostMapping("/search/picture")
    public BaseResponse<List<ImageSearchResult>> searchPictureByPicture(@RequestBody SearchPictureByPictureDTO searchPictureByPictureDTO) {
        // 检查请求参数是否为空
        ThrowUtils.throwIf(searchPictureByPictureDTO == null, ErrorCode.PARAMS_ERROR);
        // 检查图片ID是否为空或小于等于0
        Long pictureId = searchPictureByPictureDTO.getPictureId();
        ThrowUtils.throwIf(pictureId == null || pictureId <= 0, ErrorCode.PARAMS_ERROR);
        // 根据图片ID获取图片信息
        Picture oldPicture = pictureService.getById(pictureId);
        // 检查图片是否存在
        ThrowUtils.throwIf(oldPicture == null, ErrorCode.NOT_FOUND_ERROR);
        // 调用以图搜图接口，获取相似图片的搜索结果
        List<ImageSearchResult> resultList = ImageSearchApiFacade.searchImage(oldPicture.getUrl());
        // 返回搜索结果
        return ResultUtils.success(resultList);
    }


    /**
     * 颜色排序搜图功能接口
     *
     * @param searchPictureByColorDTO 以图搜图请求参数
     * @param request                 请求
     * @return 颜色排序后的图片列表
     */
    @ApiOperation(value = "颜色搜图功能接口")
    @PostMapping("/search/color")
    @SaSpaceCheckPermission(value = SpaceUserPermissionConstant.PICTURE_VIEW)
    public BaseResponse<List<PictureVO>> searchPictureByColor(@RequestBody SearchPictureByColorDTO searchPictureByColorDTO, HttpServletRequest request) {
        // 检查请求参数是否为空
        ThrowUtils.throwIf(searchPictureByColorDTO == null, ErrorCode.PARAMS_ERROR);
        // 获取当前登录用户
        User loginUser = userService.getLoginUser(request);
        // 调用颜色搜图方法，获取颜色排序后的图片列表
        List<PictureVO> pictureVOList = pictureService.searchPictureByColor(searchPictureByColorDTO, loginUser);
        // 返回搜索结果
        return ResultUtils.success(pictureVOList);
    }

    /**
     * 批量编辑图片
     *
     * @param pictureEditByBatchDTO 图片批量编辑参数
     * @param request               请求
     * @return 编辑结果
     */
    @PostMapping("/edit/batch")
    @SaSpaceCheckPermission(value = SpaceUserPermissionConstant.PICTURE_EDIT)
    public BaseResponse<Boolean> editPictureByBatch(@RequestBody PictureEditByBatchDTO pictureEditByBatchDTO, HttpServletRequest request) {
        // 校验参数
        ThrowUtils.throwIf(pictureEditByBatchDTO == null, ErrorCode.PARAMS_ERROR);
        // 获取登录用户信息
        User loginUser = userService.getLoginUser(request);
        // 执行图片批量编辑操作
        Boolean editResult = pictureService.editPictureByBatch(pictureEditByBatchDTO, loginUser);
        // 返回结果
        return ResultUtils.success(editResult);
    }

    /**
     * 创建图片 AI 扩图任务
     *
     * @param createPictureOutPaintingTaskDTO 创建图片 AI 扩图任务参数
     * @param request                         请求
     * @return 创建的响应结果
     */
    @PostMapping("/out_painting/create_task")
    @SaSpaceCheckPermission(value = SpaceUserPermissionConstant.PICTURE_EDIT)
    public BaseResponse<CreateOutPaintingTaskResponse> createPictureOutPaintingTask(@RequestBody CreatePictureOutPaintingTaskDTO createPictureOutPaintingTaskDTO,
                                                                                    HttpServletRequest request) {
        // 校验参数
        if (createPictureOutPaintingTaskDTO == null || createPictureOutPaintingTaskDTO.getPictureId() == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 获取登录用户信息
        User loginUser = userService.getLoginUser(request);
        // 执行图片 AI 扩图任务
        CreateOutPaintingTaskResponse response = pictureService.createOutPaintingTask(createPictureOutPaintingTaskDTO, loginUser);
        // 返回结果
        return ResultUtils.success(response);
    }

    /**
     * 查询图片 AI 扩图任务状态
     *
     * @param taskId 任务 ID
     * @return 任务状态详情
     */
    @GetMapping("/out_painting/get_task")
    public BaseResponse<GetOutPaintingTaskResponse> getOutPaintingTask(String taskId) {
        // 校验参数
        ThrowUtils.throwIf(StrUtil.isBlank(taskId), ErrorCode.PARAMS_ERROR);
        // 执行查询任务状态操作
        GetOutPaintingTaskResponse taskStatus = aLiYunAiApi.getOutPaintingTask(taskId);
        // 返回结果
        return ResultUtils.success(taskStatus);
    }

}
